package com.example.async_demo.controller;

import com.example.async_demo.listener.LogEvent;
import com.example.async_demo.service.UserService;
import com.example.async_demo.utils.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description:
 * <P> Date: 2024/6/4:9:14
 */

@SuppressWarnings({"unchecked", ""})
@RestController
@RequestMapping("/async")
@EnableAsync
public class AsyncController {
    private static final Logger log = LoggerFactory.getLogger(AsyncController.class);

    @Autowired
    private ThreadPoolExecutor exampleThreadPoolExecutor;

    @Autowired
    private UserService userService;

    /**
     * 模拟 执行完增加用户后，插入日志
     */
    @PostMapping("/addUserSync")
    public AjaxResult addUserSync() {
        userService.addUser();
        userService.addLog();
        return AjaxResult.success();
    }

    /**
     * 模拟 执行完增加用户后，插入日志 使用 @Async 优化
     */
    @PostMapping("/addUserAsync")
    public AjaxResult addUser() {
        userService.addUser();
        userService.addAsyncLog();
        return AjaxResult.success();
    }

    /**
     * 模拟 执行完增加用户后，插入日志 使用 线程池 优化
     */
    @PostMapping("/addUserByThreadPool")
    public AjaxResult addUserByThreadPool() {
        userService.addUser();
        exampleThreadPoolExecutor.execute(() -> userService.addLog());
        userService.addAsyncLog();
        return AjaxResult.success();
    }

    @Autowired
    private ApplicationContext applicationContext;

    @PostMapping("/addUserByListener")
    public AjaxResult addUserByListener() {
        userService.addUser();
        LogEvent logEvent = new LogEvent("");
        //applicationContext.publishEvent(logEvent);
        return AjaxResult.success();
    }

    //@org.springframework.context.event.EventListener
    public void onApplicationEvent(LogEvent event) {
        userService.addLog();
    }
}
